package com.woniu.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.woniu.entity.PageResult;
import com.woniu.entity.Result;
import com.woniu.mapper.*;
import com.woniu.pojo.*;
import com.woniu.mapper.CarMapper;
import com.woniu.mapper.RoadPatrolMapper;
import com.woniu.mapper.SpaceMapper;
import com.woniu.pojo.Car;
import com.woniu.pojo.Order;
import com.woniu.mapper.OrderMapper;
import com.woniu.pojo.RoadPatrol;
import com.woniu.pojo.Space;
import com.woniu.service.IOrderService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.woniu.vo.*;
import com.woniu.vo.ChargeReturnVo;
import com.woniu.vo.OrderSeachByIdReturnVo;
import com.woniu.vo.OrderSeachReturnVo;
import com.woniu.vo.OrderSearchVo;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import javax.annotation.Resource;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.Date;
import java.util.Iterator;
import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author long
 * @since 2022-10-12
 */
@Service
public class OrderServiceImpl extends ServiceImpl<OrderMapper, Order> implements IOrderService {
    @Resource
    private OrderMapper orderMapper;
    @Resource
    private CarMapper carMapper;
    @Resource
    private UserMapper userMapper;
    @Resource
    private ImageMapper imageMapper;
    @Resource
    private OrderImageMapper orderImageMapper;
    @Resource
    private SpaceMapper spaceMapper;
    @Resource
    private RoadPatrolMapper roadPatrolMapper;
    @Resource
    private OrderSettlementServiceImpl orderSettlementService;

    /**
     * 分页条件查询，条件为车牌号，订单编号，时间区间
     * */
    @Override
    public PageResult search(Integer currentPage, Integer pageSize, OrderSearchVo searchVo) {
        IPage page = new Page(currentPage,pageSize);
        IPage<OrderSeachReturnVo> orderList = orderMapper.selectPageByIdNumAndTime(page,searchVo);
        return new PageResult(orderList.getTotal(),orderList.getRecords());
    }

    /**
     * 订单详情查询
     * */
    @Override
    public OrderSeachByIdReturnVo searchById(long orderId) throws ParseException {
        //根据id查询订单详情
        OrderSeachByIdReturnVo returnVo = orderMapper.selectDetailsById(orderId);
        //判断有没有查到订单
        if(returnVo != null){
            //计算时间区间,判断时间有无值
            if( returnVo.getCreateTime() != null && returnVo.getLeaveTime() != null){
                long time = returnVo.getLeaveTime().getTime() - returnVo.getCreateTime().getTime();
                //毫秒换算成分钟，设置到返回对象中
                returnVo.setParkingTime(time/1000/60);
            }
            //根据id查询订单关联的图片
            List<String> imageList = orderMapper.selectOrderImages(orderId);
            returnVo.setOrderImageList(imageList);
        }
        //如果此订单状态为进行中，则计算当前产生的费用
        //判断此订单状态
        if(returnVo.getStatus().equals("0")){
            Result result = orderSettlementService.currentCost(orderId);
            BigDecimal currentCost = (BigDecimal) result.getData();
            returnVo.setCurrentMoney(currentCost);
        }

        return returnVo;
    }

    /**
     * 根据车牌添加订单
     * */
    @Override
    public boolean saveOrder(String carNum) {
        //添加订单返回影响行数
        Long row = 0l;
        //先查询车辆表有无此牌照
        QueryWrapper<Car> wrapper = new QueryWrapper<>();
        wrapper.eq("num",carNum);
        Car car = carMapper.selectOne(wrapper);
        Order order = new Order();
        if(car == null){
            //没有查到此车辆，新增此车辆
            Car car1 = new Car();
            car1.setNum(carNum);
            carMapper.insert(car1);
            //根据添加的车辆的id 生成订单
            order.setCarId(car1.getId());
            //添加订单
            row = (long)orderMapper.insert(order);
        }else {
            //查到此车辆，则使用此车辆的id添加订单
            order.setCarId(car.getId());
            row = (long) orderMapper.insert(order);
        }
        return row > 0 ? true : false;
    }

    /**
     *根据路段id查寻收费规则
     * */
    @Override
    public List<ChargeReturnVo> searchChargeRule(long roadId) {
        return orderMapper.searchChargeRule(roadId);
    }


    /**
    * 根据id进行订单结算
    * */
    @Override
    public Order settleOrder(long orderId) {
        return null;
    }

    /**
     * 车辆驶入停车位时，录入车辆并创建订单。
     * @param magnetId 地磁id
     * @param carPlateVo 摄像机拍摄的车辆的车牌图片的车牌号码、车牌类型和车辆图片的文件名
     * @return 返回操作的结果
     */
    @Override
    public boolean createOrder(Long magnetId, CarPlateVo carPlateVo) {
        // 识别图中的车牌号码和车牌颜色
        String num = carPlateVo.getNum();
        String type = carPlateVo.getType();

        // 改变泊位状态
        QueryWrapper<Space> spaceWrapper = new QueryWrapper<>();
        spaceWrapper.eq("magnet_id", magnetId);
        Space space = spaceMapper.selectOne(spaceWrapper);
        space.setStatus("1");
        spaceMapper.updateById(space);

        // 判断车辆是否已录入数据库，如果未录入，则新建车辆。
        QueryWrapper<Car> carWrapper = new QueryWrapper<>();
        carWrapper.eq("num", num);
        Car car = carMapper.selectOne(carWrapper);
        if (car == null) {
            car = new Car();
            car.setNum(num);
            car.setType(type);
            carMapper.insert(car);
        }

        // 生成订单
        Order order = new Order();
        order.setCarId(car.getId());
            // 查询并设置订单所属的巡检员
            QueryWrapper<RoadPatrol> roadPatrolWrapper = new QueryWrapper<>();
            roadPatrolWrapper.eq("road_id", space.getRoadId());
            List<RoadPatrol> roadPatrolList = roadPatrolMapper.selectList(roadPatrolWrapper);
            order.setPatrolId(roadPatrolList.get(0).getPatrolId());
        order.setSpaceId(space.getId());
        orderMapper.insert(order);

        // 将拍摄到的车辆图片保存到数据库中的t_image表
        Image image = new Image();
        image.setUri(carPlateVo.getImageUrl());
        imageMapper.insert(image);

        // 将车辆图片与订单关联
        OrderImage orderImage = new OrderImage();
        orderImage.setOrderId(order.getId());
        orderImage.setImageId(image.getId());
        orderImageMapper.insert(orderImage);

        return true;
    }

    /**
     * 巡检员查询超过5分钟未认领的订单
     * @param patrolId 巡检员id
     * @return 返回未认领的订单
     */
    @Override
    public List<OrderWithUserIdVo> queryUnclaimedOrder(Long patrolId) {
        QueryWrapper<Order> orderWrapper = new QueryWrapper<>();
        orderWrapper.eq("status", 0)
                .eq("patrol_id", patrolId)
                .le("create_time", new Date(System.currentTimeMillis() - 5*60*1000));
        List<Order> orderList = orderMapper.selectList(orderWrapper);

        // 将Order列表转换为OrderWithUserIdVo列表
        List<OrderWithUserIdVo> voList = new ArrayList<>();
        for (Order order : orderList) {
            OrderWithUserIdVo vo = new OrderWithUserIdVo();
            BeanUtils.copyProperties(order, vo);
            voList.add(vo);
        }

        // 订单对应的车辆没有绑定用户，则为未认领
        Iterator<OrderWithUserIdVo> iterator = voList.iterator();
        while (iterator.hasNext()) {
            OrderWithUserIdVo vo = iterator.next();
            Car car = carMapper.selectById(vo.getCarId());
            vo.setUserId(car.getUserId());
            if (car.getUserId() != 0) {
                iterator.remove();
            }
        }

        return voList;
    }


    /**
     * 巡检员客户端查询有无需要处理订单
     * @param patrolId
     * @param status
     * @return
     */
    @Override
    public List<OrderSeachByIdReturnVo> searchByStatus(long patrolId,String status) {
        return orderMapper.searchByStatus(patrolId,status);
    }

    /**
     * 巡检员现场收费
     * @param orderId
     * @param money
     * @param payWay
     * @param status
     * @return
     */
    @Override
    public Boolean updateStatus(long orderId, BigDecimal money, String payWay, String status) {
        Order order = new Order();
        order.setMoney(money);
        order.setPayWay(payWay);
        order.setStatus(status);
        order.setId(orderId);
        int row = orderMapper.updateById(order);
        return row > 0 ? true : false;
    }

    /**
     * 巡检员现场取证
     * @param orderId
     * @param num
     * @param userPhone
     * @param orderImageList
     * @return
     */
    @Override
    public OrderUpdateReturnVo updateOrderById(long orderId, String num, String userPhone, List<String> orderImageList) {
        // 根据orderId查询订单
        Order order = orderMapper.selectById(orderId);
        Car car = new Car();
        car.setId(order.getCarId());
        // 设置车牌号
        car.setNum(num);
        carMapper.updateById(car);
        // 根据order表中的carId查询所属车
        Car car1 = carMapper.selectById(order.getCarId());
        User user = new User();
        user.setId(car1.getUserId());
        user.setPhone(userPhone);
        userMapper.updateById(user);
        for (String image : orderImageList) {
            Image images = new Image();
            OrderImage orderImage = new OrderImage();
            images.setUri(image);
            imageMapper.insert(images);
            orderImage.setOrderId(orderId);
            orderImage.setImageId(images.getId());
            orderImageMapper.insert(orderImage);
        }

        OrderUpdateReturnVo orderUpdateReturnVo = orderMapper.selectDetailsAndPhone(orderId);
        List<String> imageList = orderMapper.selectOrderImages(orderId);
        orderUpdateReturnVo.setOrderImageList(imageList);

        return orderUpdateReturnVo;
    }


}
